package ads_topic

import (
	"gorm.io/gorm"
	"server/global"
	"server/model/common/request"
)

type AdsTopicService struct {
}

func (adsTopicService *AdsTopicService) CreateAdsTopic(adsTopic *AdsTopic) (err error) {
	err = global.SysDB.Create(adsTopic).Error
	return err
}

func (adsTopicService *AdsTopicService) DeleteAdsTopic(adsTopic AdsTopic) (err error) {
	err = global.SysDB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Model(&AdsTopic{}).Where("id = ?", adsTopic.ID).Update("deleted_by", adsTopic.DeletedBy).Error; err != nil {
			return err
		}
		if err = tx.Delete(&adsTopic).Error; err != nil {
			return err
		}
		return nil
	})
	return err
}

func (adsTopicService *AdsTopicService) DeleteAdsTopicByIds(ids request.IdsReq, deleted_by uint) (err error) {
	err = global.SysDB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Model(&AdsTopic{}).Where("id in ?", ids.Ids).Update("deleted_by", deleted_by).Error; err != nil {
			return err
		}
		if err := tx.Where("id in ?", ids.Ids).Delete(&AdsTopic{}).Error; err != nil {
			return err
		}
		return nil
	})
	return err
}

func (adsTopicService *AdsTopicService) UpdateAdsTopic(adsTopic AdsTopic) (err error) {
	err = global.SysDB.Save(&adsTopic).Error
	return err
}

func (adsTopicService *AdsTopicService) GetAdsTopicById(id uint) (adsTopic AdsTopic, err error) {
	err = global.SysDB.Where("id = ?", id).First(&adsTopic).Error
	return
}

func (adsTopicService *AdsTopicService) GetAdsTopicInfoList(info AdsTopicSearch) (list []AdsTopic, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.SysDB.Model(&AdsTopic{})
	var adsTopics []AdsTopic
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.Name != "" {
		db = db.Where("name LIKE ?", "%"+info.Name+"%")
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	err = db.Limit(limit).Offset(offset).Find(&adsTopics).Error
	return adsTopics, total, err
}

func (adsTopicService *AdsTopicService) GetAllAdsTopics() (adsTopic []AdsTopic, err error) {
	err = global.SysDB.Find(&adsTopic).Error
	return adsTopic, err
}

func (adsTopicService *AdsTopicService) GetAdsTopic() (adsTopic []AdsTopic, err error) {
	err = global.SysDB.Find(&adsTopic).Error
	return adsTopic, err
}
